package org.colcon.web.client.ui;

import org.colcon.web.client.Collective_Congress;
import org.colcon.web.client.ui.panel.UserPanel;
import org.colcon.web.model.framework.IContainer;
import org.colcon.web.model.framework.IItem;
import org.colcon.web.model.framework.ILinkContainer;
import org.colcon.web.model.framework.IUser;
import org.colcon.web.model.parsers.CLIParser;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;

public class LinkPanel extends ClickablePanel 
{
	private String path;
	
	public LinkPanel(Collective_Congress client, String text, String path)
	{
		this(client, "link", text, path);
	}
	
	public LinkPanel(Collective_Congress client, String style, String text, String path) 
	{
		super(client, style, text);
		
		this.path = path;
	}

	public String getPath()
	{
		return path;
	}
	
	public void click() 
	{
		getBodyPanel().clear();
		
		//if(!getClient().loggedIn())
		//{
		//	getBodyPanel().add(new LoginPanel(getClient()));
		//	return;
		//}
		
		getBodyPanel().add(new Label("Loading..."));
		
		getService().get(path, new AsyncCallback<String>()
		{
			public void onFailure(Throwable caught)
			{
				getBodyPanel().clear();
				getBodyPanel().add(new Label("failed to get item " + path));
			}
			
			public void onSuccess(String str)
			{
				getBodyPanel().clear();
				
				if(str == null)
				{
					getBodyPanel().add(new Label("failed to get item '" + path + "'"));
					return;
				}
				
				ItemPanel panel;
					
				IItem item = CLIParser.parseItem(str);
				
				if(item == null)
				{
					getBodyPanel().add(new Label("failed to get item '" + path + "'"));
					return;
				}
				
				if(item instanceof IContainer)
				{
					// TODO: does this need to be hard-coded?
					if(item.getPath().equals("colcon/news"))
						panel = new ListPanel(getClient(), (IContainer) item);
					else if(item instanceof IUser)
						panel = new UserPanel(getClient(), (IUser) item);
					else if(item instanceof ILinkContainer)
						panel = new LinkContainerPanel(getClient(), (ILinkContainer) item);
					else
						panel = new ContainerPanel(getClient(), (IContainer) item);
				}
				
				else
					panel = new ItemPanel(getClient(), item);
				
				getBodyPanel().add(panel);
			}
		});
	}
}
